package com.jinzhi.jzweb.controller.api;

import com.baomidou.mybatisplus.annotations.TableField;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.domain.UserDO;
import com.jinzhi.jzapi.utils.JWTUtil;
import com.jinzhi.jzapi.utils.RedisUtil;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.DateUtil;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang.math.Fraction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * @author mengzhichao
 * @create 2023-05-05-10:14
 */
@RestController
@RequestMapping("/jzApi/ApiJazUserDemand")
public class ApiJazUserDemandController {

    @Autowired
    private UserService userService; //用户表

    @Autowired
    private JazUserDemandService jazUserDemandService; //用户需求表

    @Autowired
    private JazUserAuntService jazUserAuntService; //月嫂表


    @Autowired
    private JazUserOrderService jazUserOrderService; //订单表

    @Autowired
    private JazSysProjectService jazSysProjectService; //服务类型表

    @Autowired
    private JazUserIntegralService jazUserIntegralService; //积分明细表

    @Autowired
    private WxValidationService wxValidationService; //校验敏感词

    @Autowired
    private JazInterviewService jazInterviewService; //面试邀约表



    //匹配所需积分
    private double matchingIntegral = 5000;

    double getDemandTelephoneIntegral = 100; //拨打电话所需积分



    /**
     * 需求发布
     * @return
     */
    @PostMapping("/insertUserDemand")
    @Transactional
    public Result<?> insertUserDemand(JazUserDemandDO jazUserDemandDO){
        Date start = DateUtil.strToDateLong(DateUtil.dateToStr(jazUserDemandDO.getWorkDate(), Locale.CHINA) + " 00:00:00");
        Date end = DateUtil.strToDateLong(DateUtil.dateToStr(jazUserDemandDO.getEndDate(), Locale.CHINA) + " 23:59:59");
        jazUserDemandDO.setWorkDate(start);
        jazUserDemandDO.setEndDate(end);

        UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());
        userDO.setOrderPhone(jazUserDemandDO.getOrderPhone());

        jazUserDemandDO.setAuditStatus(0); //默认待审核状态
        jazUserDemandDO.setShowStatus(0); //默认展示状态
        jazUserDemandDO.setIsShow(1);//默认发布的已经查看了
        jazUserDemandDO.setCreateTime(new Date()); //创建日期字段
        jazUserDemandDO.setSysUserid(userDO.getId()); //发布人

//        String  content =  jazUserDemandDO.getTitle() + "" + jazUserDemandDO.getAddress() + "" + jazUserDemandDO.getWorkContent() + "" + jazUserDemandDO.getWorkRequire();
//        Map validation = wxValidationService.validation(content);
//        if(Integer.parseInt(validation.get("errcode").toString())!=0){
//            System.out.println("错误信息"+validation.get("errmsg")+"状态码"+validation.get("errcode"));
//            return Result.fail("内部接口效验失败");
//        }
//        Map map  = (Map) validation.get("result");
//        int label = (int) map.get("label");
//        //接口调用成功后效验枚举标签
//        if (label != 100){
//            //直接返回不做后续操作
//            return Result.fail("包含敏感词汇发布失败");
//        }

        userService.updateById(userDO);
        jazUserDemandService.insert(jazUserDemandDO);
        return Result.ok();
    }






    /**
     * 查询登录用户的手机号
     * @return
     */
    @GetMapping("/sleLoginUserPhone")
    public Result<?> sleLoginUserPhone(){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());
        return Result.ok(userDO.getMobile());
    }





    /**
     * 需求修改
     * @return
     */
    @PostMapping("/updateUserDemand")
    @Transactional
    public Result<?> updateUserDemand(JazUserDemandDO jazUserDemandDO){
        JazUserDemandDO updateJazUserDemandDO = jazUserDemandService.selectById(jazUserDemandDO.getId());

        if (StringUtil.notEmpty(jazUserDemandDO.getTitle())){ //标题
            updateJazUserDemandDO.setTitle(jazUserDemandDO.getTitle());
        }

        if (jazUserDemandDO.getProjectId()!=null){ //项目（服务）类型id
            updateJazUserDemandDO.setProjectId(jazUserDemandDO.getProjectId());
        }

        if (jazUserDemandDO.getSex()!=null){ //性别
            updateJazUserDemandDO.setSex(jazUserDemandDO.getSex());
        }

        if (jazUserDemandDO.getResidentHome()!=null){ //是否驻家
            updateJazUserDemandDO.setResidentHome(jazUserDemandDO.getResidentHome());
        }

        if (StringUtil.notEmpty(jazUserDemandDO.getAddress())){ //地址
            updateJazUserDemandDO.setAddress(jazUserDemandDO.getAddress());
        }

        if (jazUserDemandDO.getWorkDate() != null){ //工作开始日期
            updateJazUserDemandDO.setWorkDate(jazUserDemandDO.getWorkDate());
        }

        if (jazUserDemandDO.getEndDate() != null){ //工作结束日期
            updateJazUserDemandDO.setEndDate(jazUserDemandDO.getEndDate());
        }

        if (StringUtil.notEmpty(jazUserDemandDO.getWorkContent())){ //工作内容
            updateJazUserDemandDO.setWorkContent(jazUserDemandDO.getWorkContent());
        }

        if (StringUtil.notEmpty(jazUserDemandDO.getWorkRequire())){ //工作要求
            updateJazUserDemandDO.setWorkRequire(jazUserDemandDO.getWorkRequire());
        }

        if (jazUserDemandDO.getRestDay() != null){ //休息天数
            updateJazUserDemandDO.setRestDay(jazUserDemandDO.getRestDay());
        }

        if (jazUserDemandDO.getSalary() != null){ //薪资待遇
            updateJazUserDemandDO.setSalary(jazUserDemandDO.getSalary());
        }

        if (jazUserDemandDO.getProjectTypeId() != null){ //项目子项
            updateJazUserDemandDO.setProjectTypeId(jazUserDemandDO.getProjectTypeId());
        }

        if (jazUserDemandDO.getOrderPhone() != null){ //手机号码
            UserDO getUser = JWTUtil.getUser();
            UserDO userDO = userService.selectById(getUser.getId());
            userDO.setOrderPhone(jazUserDemandDO.getOrderPhone());
            userService.updateById(userDO);
        }

        updateJazUserDemandDO.setUpdateTime(new Date()); //修改时间
        updateJazUserDemandDO.setAuditStatus(0);//改为待审核状态
        jazUserDemandService.updateById(updateJazUserDemandDO);
        return Result.ok();
    }




    /**
     * 需求取消
     * @return
     */
    @PostMapping("/cancelDemand")
    public Result<?> cancelDemand(String id){
        JazUserDemandDO jazUserDemandDO = jazUserDemandService.selectById(id);
        jazUserDemandDO.setAuditStatus(2); //已取消
        jazUserDemandService.updateById(jazUserDemandDO);
        return Result.ok();
    }



    /**
     * 需求删除
     * @return
     */
    @PostMapping("/deleteDemand")
    public Result<?> deleteDemand(String id){
        jazUserDemandService.deleteById(Long.valueOf(id)); //删除
        return Result.ok();
    }






    /**
     * 判断是否完成三单
     * @return
     */
    @GetMapping("/isUserDemandById")
    public Result<?> isUserDemandById(){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());

        EntityWrapper<JazUserAuntDO> jazUserAuntDOWrapper = new EntityWrapper<JazUserAuntDO>();
        jazUserAuntDOWrapper.eq("sys_userid",userDO.getId());
        jazUserAuntDOWrapper.eq("audit_result","0");
        JazUserAuntDO isjazUserAuntDO = jazUserAuntService.selectOne(jazUserAuntDOWrapper);
        if (isjazUserAuntDO == null){  //如果 == null表示没有认证月嫂
            return Result.ok(1); //普通用戶可以直接查看
        }
        EntityWrapper<JazUserAuntDO> wrapper=new EntityWrapper<JazUserAuntDO>();
        wrapper.eq("sys_userid",userDO.getId());
        JazUserAuntDO jazUserAuntDO = jazUserAuntService.selectOne(wrapper);
        if (jazUserAuntDO == null){
            return Result.ok(0); //未完成3单
        }
        if (3 > jazUserAuntDO.getOrderCount()){
            return Result.ok(0); //未完成3单
        }
        return Result.ok(1); //完成三单以上
    }





    /**
     * 需求回显查询
     * @return
     */
    @GetMapping("/echoUserDemandById")
    public Result<?> echoUserDemandById(String id){
        JazUserDemandDO jazUserDemandDO = jazUserDemandService.selectById(id);
        UserDO userDO = userService.selectById(jazUserDemandDO.getSysUserid());
        jazUserDemandDO.setOrderPhone(userDO.getOrderPhone());
        Long projectId = jazUserDemandDO.getProjectId();
        JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(projectId);
        jazUserDemandDO.setProjectName(jazSysProjectDO.getName());
        jazUserDemandDO.setMultipleChoice(jazSysProjectDO.getMultipleChoice());
        jazUserDemandDO.setProjectTypeName(splitStrArrayList(jazUserDemandDO.getProjectTypeId()));
        return Result.ok(jazUserDemandDO);
    }


    /**
     * 邀约回显查询
     * @return
     */
    @GetMapping("/echoInterviewById")
    public Result<?> echoInterviewById(String id){
        JazInterviewDO jazInterviewDO = jazInterviewService.selectById(id);
        JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(jazInterviewDO.getProjectId());//查询服务表
        jazInterviewDO.setProjectName(jazSysProjectDO.getName());
        return Result.ok(jazInterviewDO);
    }





    private String jmMobile(String mobile) {
        mobile = mobile.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return mobile;
    }


    private static String bs = ",";


    private static List<String> splitStrArrayList(String str) {
        List<String> stringList = new ArrayList<>();
        if (str != null) {
            String[] strs = str.split(bs);
            stringList.addAll(Arrays.asList(strs));
            return stringList;
        }
        return null;
    }


    /**
     * 判断用户积分是否够匹配
     * @return
     */
    @GetMapping("/isUserIntegral")
    public Result<?> isUserIntegral(){
        UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());
//        UserDO userDO = userService.selectById(1328881670693347330L);
        String currentPoints = userDO.getCurrentPoints(); //积分数
        if (Double.valueOf(currentPoints) < matchingIntegral) { //小于5000积分不足
            return Result.ok(0);
        }
        return Result.ok(1);
    }






    /**
     * 我的需求查询
     * status : 0 审核中 1 已通过 2 已拒绝 3 已取消
     * @return
     */
    @GetMapping("/getUserDemand")
    public Result<?> getUserDemand(String status){
        UserDO getUser = JWTUtil.getUser();
		UserDO userDO = userService.selectById(getUser.getId());

        EntityWrapper<JazUserDemandDO> wrapper=new EntityWrapper<JazUserDemandDO>();
        wrapper.eq("sys_userid",userDO.getId());
        if (status.equals("0")){ //待审核
            wrapper.eq("audit_status",0);
        }
        if (status.equals("1")){ //已通过
            wrapper.eq("audit_status",1);
            wrapper.eq("audit_result",0);
        }
        if (status.equals("2")){ //已拒绝
            wrapper.eq("audit_status",1);
            wrapper.eq("audit_result",1);
        }
        if (status.equals("3")){ //已取消
            wrapper.eq("audit_status",2);
        }
        wrapper.orderBy ("create_time",false);
        List<JazUserDemandDO> jazUserDemandDOs = jazUserDemandService.selectList(wrapper);

        for (int i=0;i<jazUserDemandDOs.size();i++){
            JazUserDemandDO jazUserDemandDO = jazUserDemandDOs.get(i);
            jazUserDemandDO.setSex(jazUserDemandDO.getSex().equals("1")?"男":"女");
            jazUserDemandDO.setResidentHome(jazUserDemandDO.getResidentHome().equals("1")?"否":"是");
//            if (jazUserDemandDO.getAge().equals("1")){
//                jazUserDemandDO.setAge("35岁以下");
//            }else if (jazUserDemandDO.getAge().equals("2")){
//                jazUserDemandDO.setAge("36-40岁");
//            }else if (jazUserDemandDO.getAge().equals("3")){
//                jazUserDemandDO.setAge("41-45岁");
//            }else if (jazUserDemandDO.getAge().equals("4")){
//                jazUserDemandDO.setAge("50岁以上");
//            }
            JazSysProjectDO jazSysProjectDO = jazSysProjectService.selectById(jazUserDemandDO.getProjectId()); //查询服务项目表
            jazUserDemandDO.setProjectName(jazSysProjectDO.getName());
        }

        return Result.ok(jazUserDemandDOs);
    }





    /**
     * 是否有新需求
     * 0.无 1.有
     * @return
     */
    @GetMapping("/isUserDemandNew")
    public Result<?> isUserDemandNew(){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());

        Date start = DateUtil.strToDateLong(DateUtil.dateToStr(new Date(), Locale.CHINA) + " 00:00:00");
        Date end = DateUtil.strToDateLong(DateUtil.dateToStr(new Date(), Locale.CHINA) + " 23:59:59");
        EntityWrapper<JazUserDemandDO> wrapper=new EntityWrapper<JazUserDemandDO>();
        wrapper.ge("create_time",start);
        wrapper.lt("create_time",end);
        wrapper.eq("sys_userid",userDO.getId());
        wrapper.eq("is_show",0); //未查看
        List<JazUserDemandDO> jazUserDemandDOS = jazUserDemandService.selectList(wrapper);
        if (jazUserDemandDOS == null){
            return Result.ok(0);
        }
        if (jazUserDemandDOS.size()>0){
            return Result.ok(1); //你有一条新需求
        }else {
            return Result.ok(0);
        }
    }




    /**
     * 修改需求查看状态
     * 0.未查看 1.已查看
     * @return
     */
    @GetMapping("/updateDemandNewShow")
    public Result<?> updateDemandNewShow(){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());

        Date start = DateUtil.strToDateLong(DateUtil.dateToStr(new Date(), Locale.CHINA) + " 00:00:00");
        Date end = DateUtil.strToDateLong(DateUtil.dateToStr(new Date(), Locale.CHINA) + " 23:59:59");
        EntityWrapper<JazUserDemandDO> wrapper=new EntityWrapper<JazUserDemandDO>();
        wrapper.ge("create_time",start);
        wrapper.lt("create_time",end);
        wrapper.eq("sys_userid",userDO.getId());
        wrapper.eq("is_show",0); //未查看
        List<JazUserDemandDO> jazUserDemandDOS = jazUserDemandService.selectList(wrapper);
        if (jazUserDemandDOS.size()>0){
            for (int i=0;i<jazUserDemandDOS.size();i++){
                jazUserDemandDOS.get(i).setIsShow(1); //已经查看
            }
            jazUserDemandService.updateBatchById(jazUserDemandDOS);
        }
        return Result.ok();
    }






    /**
     * 扣除积分接口
     * @return
     */
    @PostMapping("/deductionIntegral")
    @Transactional
    public Result<?> deductionIntegral(){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());


        EntityWrapper<JazUserOrderDO> entityWrapper =new EntityWrapper();
        entityWrapper.eq("order_source",1);//来源
        entityWrapper.and().eq("initiate_id",getUser.getId()).or().eq("signing_id",getUser.getId());
        entityWrapper.ne("status",2); //不等于已完成
        //订单来自客服
        List<JazUserOrderDO> jazUserOrderDOS = jazUserOrderService.selectList(entityWrapper);
        if (jazUserOrderDOS.size()>0){
            return Result.ok();
        }
        //积分扣除
        userDO.setCurrentPoints(String.valueOf(Double.valueOf(userDO.getCurrentPoints()) - matchingIntegral));

        JazUserIntegralDO jazUserIntegralDO = new JazUserIntegralDO();
        jazUserIntegralDO.setIntegralDetail("-"+matchingIntegral); //积分
        jazUserIntegralDO.setSysUserid(userDO.getId()); //用户id
        jazUserIntegralDO.setIntegralTime(new Date()); //时间
        jazUserIntegralDO.setIntegralWay("匹配月嫂"); //用途
        jazUserIntegralDO.setCurrentIntegral(userDO.getCurrentPoints()); //当前积分
        jazUserIntegralService.insert(jazUserIntegralDO);

        userService.updateById(userDO);
        return Result.ok();
    }








    /**
     * 是否使用积分查看需求电话号码
     * @return
     */
    @GetMapping("/isSelDemandTelephone")
    public Result<?> isSelDemandTelephone (String id){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());
        String key = "selDemandTelephone" + userDO.getId() + id;
        if (RedisUtil.get(key) == null){
            return Result.ok(0); //已过期不能查看
        }else {
            return Result.ok(1); //可以查看
        }
    }



    /**
     * 查询需求电话扣除积分
     * @return
     */
    @GetMapping("/selDemandTelephone")
    public Result<?> selDemandTelephone(String id){
        UserDO getUser = JWTUtil.getUser();
        UserDO userDO = userService.selectById(getUser.getId());

        String key = "selDemandTelephone" + userDO.getId() + id;

        if (userDO.getCurrentPoints() == null){
            userDO.setCurrentPoints("0"); //如果为null就默认0积分
        }

        if (Double.valueOf(userDO.getCurrentPoints()) < getDemandTelephoneIntegral){
            return Result.ok(0);
        }
        userDO.setCurrentPoints(String.valueOf(Double.valueOf(userDO.getCurrentPoints()) -  getDemandTelephoneIntegral));

        JazUserIntegralDO jazUserIntegralDO = new JazUserIntegralDO();
        jazUserIntegralDO.setIntegralDetail("-"+getDemandTelephoneIntegral); //积分
        jazUserIntegralDO.setSysUserid(userDO.getId()); //用户id
        jazUserIntegralDO.setIntegralTime(new Date()); //时间
        jazUserIntegralDO.setIntegralWay("查看需求电话"); //用途
        jazUserIntegralDO.setCurrentIntegral(userDO.getCurrentPoints()); //当前积分
        jazUserIntegralService.insert(jazUserIntegralDO);

        userService.updateById(userDO);
        RedisUtil.set(key,"查询需求电话24小时内有效",86400);
        return Result.ok();
    }



}
